import Vue from 'vue';
import store from '@/store';

class Socket {
	constructor(options) {
		//地址
		this.socketUrl = 'wss://im.haoyangsoft.com/wss';
		this.socketStart = false;
		this.monitorSocketError();
		this.monitorSocketClose();
		this.socketReceive();
	}
	init(callback) {
		const _this = this;
		if(this.socketStart){
			console.log('webSocket已经启动了');
		}else{
			uni.connectSocket({
				url: this.socketUrl,
				method: 'GET'
			});
			uni.onSocketOpen((res) => {
				this.socketStart = true;
				callback && callback()
				console.log('WebSocket连接已打开！');
			});
			setTimeout(() => {
				_this.getHeartbeat();
			}, 5e4);
		}
	}
	//Socket给服务器发送消息
	send(data, callback) {
		const _this = this;
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success: () => {
				callback && callback(true);
			},
			fail: () => {
				callback && callback(false);
			}
		});
	}
	//Socket接收服务器发送过来的消息
	socketReceive() {
		const _this = this;
		uni.onSocketMessage(res=> {
			let data = JSON.parse(res.data);
			//console.log('收到服务器内容：', data);
			// 绑定设备
			data.type === "connect" && Vue.prototype.$u.post('/api/chat/register',{client_id:data.client_id}).then(res=>{
				
			},err=>{
				this.closeSocket()
				setTimeout(()=>{
					this.init()
				},1000)
			})
			// 处理未读消息
			if(data.type == "message"){
				// 发送者id
				//let id = data.data.send_id.split('_')[1]
				// uview vuex 持久化
				// store.commit('add_message_list',{
				// 	type:data.data.type,
				// 	content:data.data.content,
				// 	accessory:data.data.accessory,
				// 	id:id
				// })
			}
			_this.acceptMessage && _this.acceptMessage(data);
		});
	}
	//关闭Socket
	closeSocket() {
		uni.closeSocket();
		_this.socketStart = false;
	}
	//监听Socket关闭
	monitorSocketClose() {
		const _this = this;
		uni.onSocketClose(function(res) {
			console.log('WebSocket 已关闭！');
			_this.socketStart = false;
			setTimeout(function() {
				_this.init();
			}, 3000);
		});
	}
	//监听Socket错误
	monitorSocketError() {
		const _this = this;
		uni.onSocketError(function(res) {
			_this.socketStart = false;
			console.log('WebSocket连接打开失败，请检查！');
		});
	}
	//心跳
	getHeartbeat() {
		const _this = this;
		this.send({
			type: "ping"
		}, (val) => {
			setTimeout(() => {
				if (val) {
					_this.getHeartbeat();
				} else {
					_this.init();
				}
			}, 5e4);
		});
	}
};
const socket = new Socket();
export default socket;
